<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Admin_Ticket extends Controller_Admin_Base
{
    public function action_index()
    {
        $ticket_id = $this->request->param('ticket_id') ? $this->request->param('ticket_id') : null;
        
        $ticket    = ORM::factory('ticket')->filter($ticket_id);
        $mailbox   = ORM::factory('mailbox', $ticket->mailbox_id);
        
        if (HTTP_Request::POST == $this->request->method()) {
            $type           = $this->request->post('replyMode');    
            $text           = $this->request->post('reply'); 
            $status         = $this->request->post('status'); 
            $assigned       = $this->request->post('owner');
            $file_infos     = $this->request->post('file_info'); 
            
            $attachments = array();
            if ($file_infos) {
                foreach ($file_infos as $file_info) {
                    $file_info = json_decode($file_info, true);
                    $attachments[] = $file_info;        
                }
            }
            
            try {
                if ($type == 'reply') {
                    $reply = ORM::factory('reply')->add_reply($ticket, $text, null, null, null, $attachments);                    
                } else if ($type == 'note') {
                    $note = ORM::factory('note')->add_note($ticket, $text, $attachments);                        
                } else {
                    throw new Exception('Нет такого типа');
                }
                
                if ($status != $ticket->status) {
                    $ticket->edit_ticket_status($status);    
                }
                if ($assigned != $ticket->assigned_id) {
                    $ticket->edit_ticket_assigned($assigned);   
                }

                Request::current()->redirect(Helper_Admin::ticket_url($ticket)); 
            } catch (Model_Exception $e) {
 
            }
        }
        
        $content = new View('admin/ticket/index_tpl'); 
        $content->ticket  = $ticket;
        $content->mailbox = $mailbox;
        $content->available_statuses = ORM::factory('ticket')->get_available_statuses();
        $content->filter  = $ticket->get_ticket_filter();
        /*$content->replies = ORM::factory('reply')->get_replies($ticket);
        $content->notes   = ORM::factory('note')->get_notes($ticket);
        $content->logs    = ORM::factory('log')->get_logs($ticket); */
        $list  = array();
        $_list = array_merge(
                    ORM::factory('reply')->get_replies($ticket),
                    ORM::factory('note')->get_notes($ticket),
                    ORM::factory('log')->get_logs($ticket)
        );
        $n = 0;
        foreach ($_list as $item) {
            $list[$item->created.'-'.$n] = $item;
            $n++;    
        }
        krsort($list);
        $content->list = $list;
        $content->similar_tickets = $ticket->get_tickets_from_same_client($mailbox);
        
        //$user = Model_Auth::instance()->get_user();  
        $content->users = ORM::factory('user')->get_users_by_list($list);
        $content->all_users = ORM::factory('user')->get_all_users(); 
        $content->patterns = ORM::factory('pattern')->get_patterns($mailbox); 
        $this->print_template($ticket->subject.' - Тикет', $content);     
    }
    
    public function action_add()
    { 
        $mailbox_hash = $this->request->param('mailbox_hash') ? $this->request->param('mailbox_hash') : null;
        $mailbox      = ORM::factory('mailbox')->get_mailbox_by_hash($mailbox_hash);
        
        if (HTTP_Request::POST == $this->request->method()) {
            $type           = $this->request->post('type');   
            $client_name    = $this->request->post('customer');
            $email          = $this->request->post('client_email'); 
            $phone          = $this->request->post('phone'); 
            $subject        = $this->request->post('subject'); 
            $text           = $this->request->post('reply'); 
            $status         = $this->request->post('status'); 
            $assigned       = $this->request->post('owner'); 
            
            $file_infos     = $this->request->post('file_info'); 
            
            $attachments = array();
            if ($file_infos) {
                foreach ($file_infos as $file_info) {
                    $file_info = json_decode($file_info, true);
                    $attachments[] = $file_info;        
                }
            }
                  
            try {        
                $ticket = ORM::factory('ticket')->add_ticket($mailbox, $type, $client_name, $email, $phone, $subject, $text, $status, $assigned, null, $attachments);

                $filter = $ticket->get_ticket_filter();
                Request::current()->redirect(Helper_Admin::mailbox_url($mailbox, $filter)); 
            } catch (Model_Exception $e) {
                //die($e->getMessage());    
            }
        }
       
        $content = new View('admin/ticket/add_tpl');
        $content->mailbox = $mailbox;  
        $content->all_users = ORM::factory('user')->get_all_users();
        $content->patterns = ORM::factory('pattern')->get_patterns($mailbox);      
        $this->print_template('Создать тикет', $content);   
    }
    
    public function action_assign()
    { 
        $ticket_id   = $this->request->param('ticket_id') ? $this->request->param('ticket_id') : null; 
        $assigned_id = $this->request->param('assigned_id') ? $this->request->param('assigned_id') : null; 
        
        $ticket = ORM::factory('ticket')->filter($ticket_id);
        $assigned = 0;
        if ($assigned_id) {
            $assigned = ORM::factory('user', $assigned_id);    
        }
        
        $ticket->edit_ticket_assigned($assigned);
        Request::current()->redirect(Helper_Admin::ticket_url($ticket)); 
    }
    
    public function action_status()
    { 
        $ticket_id = $this->request->param('ticket_id') ? $this->request->param('ticket_id') : null; 
        $status    = $this->request->param('status') ? $this->request->param('status') : null; 
        
        $ticket = ORM::factory('ticket')->filter($ticket_id);
        
        $ticket->edit_ticket_status($status);
        Request::current()->redirect(Helper_Admin::ticket_url($ticket)); 
    }
    
    public function action_delete()
    { 
        $ticket_id = $this->request->param('ticket_id') ? $this->request->param('ticket_id') : null;  
        
        $ticket = ORM::factory('ticket')->filter($ticket_id);
        $mailbox = ORM::factory('mailbox', $ticket->mailbox_id);
        $filter  = $ticket->get_ticket_filter();
        
        $ticket->mark_ticket_as_deleted();
        Request::current()->redirect(Helper_Admin::mailbox_url($mailbox, $filter)); 
    }
    
    public function action_uploadfiles()
    {
        $mailbox_hash = $this->request->param('mailbox_hash') ? $this->request->param('mailbox_hash') : null;
        $mailbox      = ORM::factory('mailbox')->get_mailbox_by_hash($mailbox_hash);
        
        $result = array(
            'status' => 'error',            
        );
        
        if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
            $attachments_dir = APPPATH.'../media/uploads/attachments/'.$mailbox->id;
            if (!is_dir($attachments_dir)) {
                $old = umask(0);
                mkdir($attachments_dir, 0777);
                umask($old);    
            }
         
            $new_filename = Model_Main::translit(time().'_'.$_FILES['file']['name']);
            $new_path     = $attachments_dir.'/'.$new_filename;
            $new_url      = '/media/uploads/attachments/'.$mailbox->id.'/'.$new_filename;
            $new_size     = filesize($_FILES['file']['tmp_name']);
            if (move_uploaded_file($_FILES['file']['tmp_name'], $new_path)) {
                $file_info = array(
                    'name'     => $_FILES['file']['name'],
                    'filePath' => $new_path,
                );
                $result['status'] = 'success';
                $result['tpl'] = '<li><a target="_blank" href="'.$new_url.'" rel="draft" title="Просмотр">'.$_FILES['file']['name'].'</a>
                    <span>'.Model_Main::filesize_format($new_size).'</span>
                    <a href="#" class="remove" title="Удалить"><i class="icon-close1"></i></a>
                    <input type="hidden" name="file_info[]" value=\''.json_encode($file_info).'\' />
                </li>';
                echo json_encode($result);
                die();
            }
        }
         
        echo json_encode($result); 
        die();
    }
} 
